<script>
export default {
  name:"role",
  mounted() {
    this.selectRoleByCondition()
    this.$http.get("menu/selectAll").then((resp)=>{
      this.tableMenus=resp.data.data;
      // this.tableMenu = this.tableMenus.slice(0,10)
    }).catch(error=>{

    })
  },
  methods:{
    //select选择控制
    filterMethod(query){
      if (query == "" ) {
        return  this.tableMenu = this.tableMenus.slice(0,10)
      }else{
        let result = []
        this.tableMenus.forEach(val=>{
          if (val.menuName.indexOf(query) != -1) result.push(val)
        })
          this.tableMenu = result.slice(0,10)

      }

  },


    //普通删除
    deleteByIdRole(row){
      this.roleIds=[]
      this.roleIds.push(row.roleId)
      this.$http.post("role/delete",this.roleIds).then((resp)=>{
        if (resp.data.code == 200){
          this.$message({
            showClose: true,
            message: '恭喜你，删除成功',
            type: 'success'
          });
          this.selectRoleByCondition()
        }else if (resp.data.code == 500){
          this.$message({
            showClose: true,
            message: '删除失败',
            type: 'warning'
          });
        }
      }).catch(error=>{

      })
    },
    //批量删除
    deleteByIdsRole(done){
      if (this.roleIds.length == 0){
        this.$message({
          message: '请先选择用户',
          type: 'warning'
        });
        return

      }
      this.$confirm('是否批量删除？')
          .then(_ => {
            this.$http.post("role/delete ",this.roleIds).then((resp)=>{
              if (resp.data.code == 200){
                this.$message({
                  showClose: true,
                  message: '恭喜你，删除成功',
                  type: 'success'
                });
                this.selectRoleByCondition()
              }
              done();
            }).catch(error=>{

            })

          })
          .catch(_ => {});
    },
    //多选
    handleSelectionChange(val) {
      this.roleIds=[]
      console.log(val)
      for (let i = 0; i < val.length; i++) {
        this.roleIds.push(val[i].roleId)
      }
      console.log(this.userIds)
    },

    selectRoleByCondition(){
      this.$http.post("role/select?current="+this.currentPage+"&size="+this.pageSize+"",this.role).then((resp)=>{
        this.tableData=resp.data.data.list;
        this.total = resp.data.data.total;
      }).catch(error=>{

      })
    },

    //筛选值
    searchSelect(data){
      this.role.menus = data
      console.log(this.role.menus)
    },
    //关闭弹窗
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            this.role={}
            done();
          })
          .catch(_ => {});
    },
    updateRole(row){
      this.dialogVisible=true;
      console.log(row);
      this.role=row
      this.menus=row.menus
      this.tableMenu = row.menus
      console.log(this.menus)
      this.isShow = false
    },
    //弹出框
    addRole(){
      this.isShow = true
      this.menuIds=[]
      this.dialogVisible=true;

      // this.$http.post("user/addUser",this.user).then((resp)=>{
      //
      // })
    },
    addOrUpdateRole(){
      this.menuIds=[]
      for (var i=0;i<this.menus.length;i++){
        this.menuIds.push(this.menus[i].menuId)
      }
      console.log(this.role)
      if (this.role.updateTime != "" && this.role.updateTime != null){
        //修改

        this.$http.put("role/update",this.role).then((resp)=>{
          if (resp.data.code==200){
            this.$message({
              showClose: true,
              message: '恭喜你，修改成功',
              type: 'success'
            });
            this.dialogVisible=false;
            this.role={}
            this.selectRoleByCondition()
          }
        }).catch((error)=>{
          console.log(error)
        })

      }else {
        //添加
        this.$http.post("role/add",this.role).then((resp)=>{
          if (resp.data.code==200){
            this.$message({
              showClose: true,
              message: '恭喜你，添加成功',
              type: 'success'
            });
          }
          this.dialogVisible=false;
          this.role={}
          this.selectRoleByCondition()
        }).catch((error)=>{
          console.log(error)
        })
      }

    },
    //分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.selectRoleByCondition()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.selectRoleByCondition()
    },

  },
  data() {
    var validateRoleName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('角色名称不能为空'));
      } else {
        if (value.length>20) {
          callback(new Error('角色名称过长'));
        }
        callback();
      }
    };
    var validateRoleKey = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('角色key不能为空'));

      } else {
        const regEmail = /sys(:).*(:)admin$/;
        if(this.role.roleKey != '' && !regEmail.test(this.role.roleKey)) {
          callback(new Error('格式示例 sys:*:admin'));
        }
        callback();
      }
    };
    var validateRemark = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('备注不能为空'));
      } else {
        if (value.length>200) {
          callback(new Error('备注过长'));
        }
        callback();
      }
    };
    return {
      rules: {
        roleName: [
          { validator: validateRoleName, trigger: 'blur' }
        ],
        roleKey:[
          {validator: validateRoleKey, trigger: 'change' }
        ],
        remark:[
          {validator: validateRemark, trigger: 'blur' }
        ],


      },
      //多选
      multipleSelection: [],
      roleIds:[],
      options: [
        {
          value: "",
          label: '无'
        },
        {
          value: "启用",
          label: '启用'
        }, {
          value: "禁用",
          label: '禁用'
        }],
      label:"",
      menus: [],
      menuIds: [{

      }],
      dialogVisible: false,
      //分页
      currentPage: 1,
      pageSize:5,
      total:10,
      tableMenus:[
        {
          menuId:"0",
          menuName: "",
        }
      ],
      tableMenu:[
        {
          menuId:"0",
          menuName: "",
        }
      ],

      role:{
        roleName:"",
        roleKey:"",
        roleId:"",
        remark:"",
        status:"",
        updateTime:"",
        menus:[]
      },
      tableData: [{
        menus:[{
          menuName:''
        }]
      }]
    }
  }
}
</script>

<template>
  <div>
    <h1 style="margin-left: 2%;top: 14px;position: relative">角色管理</h1>
    <div style="position: relative;margin-top:2%">

      <el-input
          placeholder="请输入角色id"
          v-model="role.roleId"
          style="width: 200px"
          clearable>
      </el-input>

      <el-input
          placeholder="请输入角色名称"
          v-model="role.roleName"
          style="width: 200px;margin-left: 2px"
          clearable>
      </el-input>

      <el-select v-model="role.status" placeholder="请选择"
                 style="margin-left: 2px;width: 100px;">
        <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            style="width: 100px">
        </el-option>
      </el-select>
      <el-button type="primary" icon="el-icon-search" style="margin-left: 15px" @click="selectRoleByCondition">搜索</el-button>
      <el-button type="danger" round style="float: right;margin-right: 35px;position: relative" @click="deleteByIdsRole">批量删除</el-button>
      <el-button type="primary" round style="float: right;margin-right: 19px;position: relative" @click="addRole">添加角色</el-button>
    </div>



    <el-table
        :data="tableData"
        border
        ref="multipleTable"
        style="width: 100%;margin-top: 1%;margin-left: 1%;border-radius: 2px"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          prop="roleId"
          label="角色id"
          width="200">
      </el-table-column>
      <el-table-column
          prop="roleName"
          label="角色名称"
          width="150">
      </el-table-column>
      <el-table-column
          prop="roleKey"
          label="角色key"
          width="150">
      </el-table-column>
      <el-table-column
          prop="remark"
          label="角色备注"
          width="180">
      </el-table-column>

      <el-table-column
          prop="status"
          label="状态"
          width="100">
      </el-table-column>


      <el-table-column
          align="center"
          prop="menus"
          label="权限名称"
          width="180">
        <template slot-scope="scope" >
          <div v-for="(item, index) in scope.row.menus" :key="index">
              {{item.menuName}}

          </div>
        </template>
      </el-table-column>

      <el-table-column
          fixed="right"
          label="操作"
          width="140">
        <template slot-scope="scope">
          <el-button @click="updateRole(scope.row)" type="text" size="small">编辑</el-button>
          <el-button @click="deleteByIdRole(scope.row)" type="text" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 2%"
    >
    </el-pagination>



    <!--添加form表单-->
    <el-dialog
        title="编辑角色"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose">
      <el-form ref="form" :model="role" label-width="80px" :rules="rules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="role.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色key" prop="roleKey">
          <el-input v-model="role.roleKey"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="role.remark"></el-input>
        </el-form-item>

        <el-form-item label="状态">
          <el-tooltip  placement="top">
            <el-switch
                v-model="role.status"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="启用"
                inactive-value="禁用">
            </el-switch>
          </el-tooltip>
        </el-form-item>

        <el-form-item label="选择权限">
          <el-select  v-model="menus"
                      value-key="menuId"
                      filterable
                      :filter-method="filterMethod"
                      multiple placeholder="请选择" style="width: 233px " @change="searchSelect">
            <el-option
                v-for="item in tableMenu"
                :key="item.menuId"
                :label="item.menuName"
                :value="item"
            >

            </el-option>
          </el-select>

        </el-form-item>


      </el-form>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addOrUpdateRole">确 定</el-button>

    </el-dialog>


  </div>
</template>

<style scoped>
.el-pagination{
  text-align: center;
}
</style>